(function () {
  var moduleList = [
    function (require, exports, module) {
      /* template */
    },
  ];

  var moduleDepIdList = [];

  var cache = {}; //异步

  function require(id, parentId) {
    var currentModuleId =
      parentId !== undefined ? moduleDepIdList[parentId][id] : id;

    var module = { exports: {} };
    var moduleFunc = moduleList[currentModuleId];
    moduleFunc((id) => require(id, currentModuleId), module, module.exports);
    return module.exports;
  }

  //JSONP作用就是从全局cache里面读取到刚才存储的resolve方法
  //在resolve里面 通过函数执行把模块导出的对象resolve出去
  //就可以在then里面拿到模块
  window.__JSONP = function (chunkId, moduleFunc) {
    var currentChunkStatus = cache[chunkId];
    var resolve = currentChunkStatus[0];
    var module = { exports: {} };
    moduleFunc(require, module, module.exports);
    resolve(module.exports);
  };

  //对于import() 遇到require.ensure 通过jsonp进行异步加载
  //通过全局的对象对当前模块的状态进行缓存
  //没有就创建一个script标签通过jsonp形式异步通过trunkId拿到打包结果
  //最终返回一个promise
  //把两个状态添加到全局的cache
  //第一个是resolve状态 记录当前status 为true就是还在加载
  //需要用数组缓存多个状态

  require.ensure = function (chunkId, parentId) {
    var currentModuleId =
      parentId !== undefined ? moduleDepIdList[parentId][chunkId] : chunkId;
    var currentChunkStatus = cache[currentModuleId];

    if (currentChunkStatus === undefined) {
      //没有
      var $script = document.createElement("script");
      // $script.src = chunkId + currentChunkStatus + ".js";
      $script.src = "chunk_" + chunkId + ".js";
      document.body.appendChild($script);

      var promise = new Promise(function (resolve) {
        var chunkCache = [resolve];
        chunkCache.status = true;
        cache[currentModuleId] = chunkCache;
      });
      cache[currentModuleId].push(promise);

      return promise;
    }

    if (currentChunkStatus.status) {//加载中还是true
      return currentChunkStatus[1];//返回promise实例
    }

    return chunkCache;
  };

  // require(0);
  moduleList[0](require, null, null);
})();
